package com.gi.profiler.controllers;

import java.sql.SQLException;
import java.util.List;

import android.util.Log;

import com.gi.profiler.db.DatabaseHelper;
import com.gi.profiler.db.DatabaseHelperManager;
import com.gi.profiler.model.Profile;

public class ProfileController {

    private final String LOG_NAME = getClass().getName();

    // private static ProfileController instance = null;

    /**
     * Instantiates a new profile controller. Making it a singleton may cause
     * memory leak if it is not used that frequently. .. check it later
     */
    public ProfileController() {
    }

    // public static ProfileController getInstance(){
    // if(instance == null)
    // instance = new ProfileController();
    // return instance;
    // }

    public List<Profile> getProfileList() {
	List<Profile> profileLst = null;
	try {
	    profileLst = DatabaseHelperManager.getHelper().getProfileDao().queryForAll();
	} catch (SQLException e) {
	    Log.e(LOG_NAME, e.getMessage());
	} finally {
	    DatabaseHelperManager.releaseHelper();
	}

	return profileLst;
    }

    public Profile getProfileById(int id) {
	Profile profile = null;
	try {
	    profile = DatabaseHelperManager.getHelper().getProfileDao().queryForId(id);
	} catch (SQLException e) {
	    Log.e(LOG_NAME, e.getMessage());
	} finally {
	    DatabaseHelperManager.releaseHelper();
	}

	return profile;
    }

    /**
     * Gets the filled profile by id. If a foreign object is null that means
     * there is no change in the corresponding fields
     * 
     * TODO: check which is faster , checking if null or refreshment anyways
     * 
     * @param id
     *            the id
     * @return the filled profile by id
     */
    public Profile getFilledProfileById(Integer id) {
	Profile profile = null;
	DatabaseHelper dbHelper = DatabaseHelperManager.getHelper();
	try {
	    long startTime = System.currentTimeMillis();
	    Log.i(LOG_NAME, "Start getFilledProfileById " + id);
	    profile = dbHelper.getProfileDao().queryForId(id);
	    // if (profile.getSoundSettings() != null)
	    dbHelper.getSoundSettingsDao().refresh(profile.getSoundSettings());
	    // if (profile.getConnectivitySettings() != null)
	    dbHelper.getConnSettingsDao().refresh(profile.getConnectivitySettings());
	    // if (profile.getWallpaper() != null)
	    dbHelper.getDisplayDao().refresh(profile.getDiplaySettings());
	    Log.i(LOG_NAME, "====================");
	    Log.i(LOG_NAME, "End : Done in " + (System.currentTimeMillis() - startTime));
	} catch (SQLException e) {
	    Log.e(LOG_NAME, e.getMessage());
	} finally {
	    DatabaseHelperManager.releaseHelper();
	}

	return profile;
    }
}
